package com.chee.plant.hibernate.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.chee.plant.hibernate.object.User;
import com.chee.plant.server.HibernateSessionFactory;

/**
 * 对应User的数据库操作
 * 
 * @author xue cb
 * 
 */
public class UserDAO extends BaseHibernateDAO {

	/**
	 * 获取所有用户
	 * 
	 * @return 所有用户列表
	 */
	@SuppressWarnings("unchecked")
	public List<User> getAllUser() {
		Session session = HibernateSessionFactory.getSession();
		String hql = "select user from User as user";
		Query query = session.createQuery(hql);
		List<User> list = query.list();
		return list;
	}

	/**
	 * 根据用户Id得到用户
	 * 
	 * @param userId
	 *            用户Id
	 * @return 特定的用户实例
	 */
	public User getUserById(Integer userId) {

		Session session = HibernateSessionFactory.getSession();
		String hql = "select user from User as user where user.Id=:userId";
		Query query = session.createQuery(hql);
		query.setInteger("userId", userId);
		return (User) query.uniqueResult();
	}

	/**
	 * 根据用户姓名得到用户
	 * 
	 * @param name
	 *            用户姓名
	 * @return 特定的用户实例
	 */
	public User getUserByName(String name) {
		Session session = HibernateSessionFactory.getSession();
		String hql = "select user from User as user where user.Name=:name";
		Query query = session.createQuery(hql);
		query.setString("name", name);
		return (User) query.uniqueResult();
	}

	/**
	 * 查询用户的头像，种植经验和等级金币数量(只查询要用到的信息，减少系统开销)
	 * 
	 * @param 用户Id
	 * @return 特定的用户实例
	 */
	public User getUserInfo(Integer userId) {
		Session session = HibernateSessionFactory.getSession();
		String hql = "select new User(Picture,CropExp,CropLevel,Gold) from User as user where user.Id=:userId";
		Query query = session.createQuery(hql);
		query.setInteger("userId", userId);
		return (User) query.uniqueResult();
	}

	/**
	 * 主方法，用于测试
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// 1,测试getAllUser()
		List<User> list = new UserDAO().getAllUser();
		// 打印用户数量
		System.out.println("当前共有" + list.size() + "用户");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(((User) (list.get(i))).getId());
		}
		System.out
				.println("分隔符 ++++++++++++++++++++++++++++++++++++++++++++++++++++");
		// 2,测试getUserInfo(Integer userId)
		// 依次输出要用到的字段
		User user = new UserDAO().getUserInfo(1);
		System.out.println(user.getPicture());
		System.out.println(user.getCropLevel());
		System.out.println(user.getGold());
		System.out.println(user.getCropExp());

	}

}
